package com.yanxin.grpc.stub.controller;

import com.yanxin.grpc.proto.activity.log;
import com.yanxin.grpc.proto.activity.rpaGrpc;
import com.yanxin.grpc.proto.activity.run_args;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;

@RestController
public class RpaController {

    @GrpcClient("rpaClientService")
    private rpaGrpc.rpaBlockingStub rpaBlockingStub;


    @GetMapping(value = "/data-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public void getDataStream(HttpServletResponse response) throws IOException {

        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
        response.setCharacterEncoding("utf-8");
        response.setStatus(HttpStatus.OK.value());
        Iterator<log> run = rpaBlockingStub.run(run_args.newBuilder()
                .setId("")
                .setUrl("")
                .setIsDebug(true)
                .build());
        while (run.hasNext()) {
            if (!response.getWriter().checkError()) {
                log next = run.next();
                String data = next.getData();
                response.getWriter().write(data);
                response.getWriter().flush();
            }
        }
    }
}
